package com.ybkj.daijia.serverUtils;

import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.rest.JSONCheckStatus;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;


public class HttpClientUtil {

    //    private static String apikey = "63bdf7028579ff2c0ab44ff787f6efb1";
    private static String apikey = "jGXd4sZhHCRUH4Hyhv80BCMQz2Shotdt";

    private static String shortUrl = "http://apis.baidu.com/3023/shorturl/shorten";//短链接生成


    private static String placeURL = "http://api.map.baidu.com/place/v2/search";

    private static String strSendURL = "http://api.map.baidu.com/geocoder/v2/";

//    private static String directSendURL = "http://api.map.baidu.com/direction/v1/routematrix";

    private static String directSendURLV2 = "http://api.map.baidu.com/routematrix/v2/driving";//驾车 directSendURL升级版本（2017年7月30日下线）

    private static String ipUrl = "http://api.map.baidu.com/location/ip";

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);


    private static String getAk() {
        List<String> aklist = new ArrayList<String>();
        aklist.add("AuNk3YS21DSmHEEvIFDf9dbD");
//		aklist.add("qUwI31Ww00t9ZEKkyQwQBwGW");
//		aklist.add("ROqEF3nPZEAAc2IXEvKhgB32");
//		aklist.add("v9IrYKFqyZogCUxc6cyegSld");
//		aklist.add("VGQdoQxhxtAb9ulMpODrDe53");
//		aklist.add("0uN3S7sy7ehZdsDm79qNtg71");
//		aklist.add("A0HgFu5ajp5KGoxoNeTL6IFr");
//		aklist.add("dSKScYEKSA9WrXX3GcMgVRg5");
//		aklist.add("pXoto9RTELxr1WN5zfoRawED");
//		aklist.add("t28R82dlBEniN6sndenOHCvb");
//		aklist.add("bMmmO1bxTXnW9SKrj0T9dcWt");
//		aklist.add("Bm3UQZegVky3xGaVQ1L9AdDR");
//		aklist.add("9TK4P0pIXOSA8F0FZNkiShqI");
//		aklist.add("dcrdrnjI8LgkiblWq39cktEF");
//		aklist.add("bexUsLb0vhLKPljWX18tq7xL");

//        aklist.add("ZPSUvtssKbBN4vkQryCRZGWq");//鲜艺 通过
//		aklist.add("8H1QBOhjG12uGXN5HZXxISVm");//肖浩 未通过
//        aklist.add("BKhZw5iA5IU7OytHEdXTIUoH");//杜伟 通过
//		aklist.add("1AhE1PSmqrn4juKa7AOh59fp");//熊鹏 未通过
//		aklist.add("fmdmjZ6XAh1G7elNGfGTQhMa");//张军 未通过

        Random rand = new Random();
        return aklist.get(rand.nextInt(aklist.size()));
    }

    public static JSONArray getPlacesByName(String placeName, String cityName) {

        try {
            StringBuilder sb = new StringBuilder();
            sb.append(placeURL);
            sb.append("?output=").append("json");
            sb.append("&region=").append(cityName);
            sb.append("&q=").append(placeName);
            sb.append("&ak=").append(getAk());
            String content = getUrl(sb.toString());

            JSONObject obj = new JSONObject(content);

            if (obj.optInt("status") == 0) {

                JSONArray ret = obj.optJSONArray("results");
                return ret;

            }

            return null;
        } catch (Exception e) {
            return null;
        }
    }

    public static JSONArray getPlacesByCityName(String placeName, String cityName) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(placeURL);
            sb.append("?output=").append("json");
            sb.append("&region=").append("{region}");
            sb.append("&query=").append("{query}");
            sb.append("&city_limit=").append("{city_limit}");
            sb.append("&ak=").append("{ak}");
            Map<String, Object> kv = new HashMap<>();
            kv.put("region", cityName);
            kv.put("query", placeName);
            kv.put("city_limit", true);
            kv.put("ak", getAk());
            String content = restGet(sb.toString(), kv);

            JSONObject obj = new JSONObject(content);
            if (obj.optInt("status") == 0) {
                JSONArray ret = obj.optJSONArray("results");
                return ret;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    public static String restGet(String url, Map<String, Object> kv) {
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class, kv);
        return result;
    }

    public static String getPlaceByLngAndLat(Double lng, Double lat) {

        String street = "";
        String name = "";
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("ak=").append(getAk());
            sb.append("&location=").append(lat + "," + lng);
            sb.append("&output=").append("json");
            sb.append("&pois=").append(1);

            String result = GetResponseDataByID(strSendURL, sb.toString());

            JSONObject obj = new JSONObject(result);

            if (obj.optInt("status") == 0) {

                JSONObject ret = obj.optJSONObject("result");

                JSONObject addressComponent = ret.optJSONObject("addressComponent");
                street = addressComponent.optString("street");

                JSONArray pois = ret.optJSONArray("pois");
                JSONObject poi = pois.getJSONObject(0);
                name = poi.optString("name");

            }
        } catch (Exception e) {

        }

        if (StringUtils.isBlank(street) && StringUtils.isBlank(name)) {
            return "未知";
        } else {
            if (StringUtils.isBlank(street)) {
                return name;
            } else if (StringUtils.isBlank(name)) {
                return street;
            } else {
                return street + " " + name;
            }
        }

    }

    public static String getCityByLngAndLat(Double lng, Double lat) {

        try {
            StringBuilder sb = new StringBuilder();
            sb.append("ak=").append(getAk());
            sb.append("&location=").append(lat + "," + lng);
            sb.append("&output=").append("json");
            sb.append("&pois=").append(0);

            String result = GetResponseDataByID(strSendURL, sb.toString());

            JSONObject obj = new JSONObject(result);

            if (obj.optInt("status") == 0) {

                JSONObject ret = obj.optJSONObject("result");

                JSONObject addressComponent = ret.optJSONObject("addressComponent");
                return addressComponent.optString("city");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public static Map<String, String> getProvinceCityByLngAndLat(Double lng, Double lat) {

        try {
            StringBuilder sb = new StringBuilder();
            sb.append("ak=").append(getAk());
            sb.append("&location=").append(lat + "," + lng);
            sb.append("&output=").append("json");
            sb.append("&pois=").append(0);

            String result = GetResponseDataByID(strSendURL, sb.toString());

            JSONObject obj = new JSONObject(result);

            if (obj.optInt("status") == 0) {

                JSONObject ret = obj.optJSONObject("result");

                JSONObject addressComponent = ret.optJSONObject("addressComponent");
                String province = addressComponent.optString("province");
                String city = addressComponent.optString("city");

                Map<String, String> map = new HashMap<String, String>();
                map.put("province", province);
                map.put("city", city);
                return map;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static Result<Map<String, Double>> getLngAndLatByPlace(
        String address, String city) {

        Result<Map<String, Double>> vo = new Result<Map<String, Double>>();

        StringBuilder sb = new StringBuilder();
        sb.append("ak=").append(getAk());
        sb.append("&address=").append(address);
        sb.append("&city=").append(city);
        sb.append("&output=").append("json");

        try {
            String result = GetResponseDataByID(strSendURL, sb.toString());

            JSONObject obj = new JSONObject(result);

            Map<String, Double> map = new HashMap<String, Double>();
            if (obj.get("status").toString().equals("0")) {

                map.put("lng",
                    Double.valueOf(obj.getJSONObject("result")
                        .getJSONObject("location").get("lng")
                        .toString()));
                map.put("lat",
                    Double.valueOf(obj.getJSONObject("result")
                        .getJSONObject("location").get("lat")
                        .toString()));

                vo.setSuccess(true);
                vo.setResult(map);
                return vo;
            }

            vo.setSuccess(false);
            return vo;

        } catch (Exception e) {
            vo.setSuccess(false);
            return vo;
        }
    }

    public static String getTimeByTwoPoints(Double fromlng, Double fromlat,
        Double tolng, Double tolat) {

        StringBuilder sb = new StringBuilder();
        sb.append(directSendURLV2);
        sb.append("?output=").append("json");
        sb.append("&origins=").append(fromlat + "," + fromlng);
        sb.append("&destinations=").append(tolat + "," + tolng);
        sb.append("&ak=").append(getAk());

        String content = getUrl(sb.toString());

        if (null != content) {

            JSONObject obj = new JSONObject(content);

            if (obj.get("status").toString().equals("0")) {

                JSONObject resultObj = obj.getJSONArray("result").getJSONObject(0);

                if (resultObj != null) {
                    JSONObject duration = resultObj.optJSONObject("duration");
                    int durationValue = duration.optInt("value");

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.add(Calendar.SECOND, durationValue);

                    return DateFormatUtils.format(calendar, "MM-dd HH:mm");
                }
            }
        }

        return "";
    }

    //
    public static String urlEncodeUTF8(String source) {
        String result = source + "wx/v1/memberOrder";
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    //
    public static String getUserInfo(String CODE, String APPID, String SECRET) {
        String GetCodeRequest =
            "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + SECRET
                + "&code=" + CODE + "&grant_type=authorization_code";
        String info = getUrl(GetCodeRequest);

        try {
            if (StringUtils.isNotBlank(info)) {
                JSONObject obj = new JSONObject(info);
                Object openidObj = obj.get("openid");
                if (null != openidObj) {
                    String openId = obj.get("openid").toString();
                    return openId;
                }
            }
        } catch (JSONException e) {
            //e.printStackTrace();
        }
        return "";
    }

    public static String getHaMTimeByTwoPoints(Double fromlng, Double fromlat,
        Double tolng, Double tolat) {

        StringBuilder sb = new StringBuilder();
        sb.append(directSendURLV2);
        sb.append("?output=").append("json");
        sb.append("&origins=").append(fromlat + "," + fromlng);
        sb.append("&destinations=").append(tolat + "," + tolng);
        sb.append("&ak=").append(getAk());

        String result = getUrl(sb.toString());

        JSONObject obj = new JSONObject(result);

        if (obj.get("status").toString().equals("0")) {
            JSONObject resultObj = obj.getJSONArray("result").getJSONObject(0);

            Integer durationValue = Integer
                .parseInt(resultObj.getJSONObject("duration").get("value").toString());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            if (null != durationValue) {
                calendar.add(Calendar.SECOND, durationValue);
            }
            Date arriveTime = calendar.getTime();

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            String dateStr = sdf.format(arriveTime);
            return dateStr;
        }

        return "";
    }

    public static Date getDateByTwoPoints(Double fromlng, Double fromlat,
        Double tolng, Double tolat) {

        StringBuilder sb = new StringBuilder();
        sb.append(directSendURLV2);
        sb.append("?output=").append("json");
        sb.append("&origins=").append(fromlat + "," + fromlng);
        sb.append("&destinations=").append(tolat + "," + tolng);
        sb.append("&ak=").append(getAk());

        String result = getUrl(sb.toString());

        JSONObject obj = new JSONObject(result);

        if (obj.get("status").toString().equals("0")) {

            JSONObject resultObj = obj.getJSONArray("result").getJSONObject(0);

            Integer durationValue = Integer.parseInt(resultObj.getJSONObject("duration")
                .get("value").toString());

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            if (null != durationValue) {
                calendar.add(Calendar.SECOND, durationValue);
            }
            Date arriveTime = calendar.getTime();

            return arriveTime;

        }

        return null;
    }

    public static String getDistanceAndTimeByTwoPoints(Double fromlng,
        Double fromlat, Double tolng, Double tolat) {

        StringBuilder sb = new StringBuilder();
        sb.append(directSendURLV2);
        sb.append("?output=").append("json");
        sb.append("&origins=").append(fromlat + "," + fromlng);
        sb.append("&destinations=").append(tolat + "," + tolng);
        sb.append("&ak=").append(getAk());

        String result = getUrl(sb.toString());

        JSONObject obj = new JSONObject(result);

        if (obj.get("status").toString().equals("0")) {

            JSONObject resultObj = obj.getJSONArray("result").getJSONObject(0);

            String distanceTxt = resultObj.getJSONObject("distance").get("text").toString();
            Integer durationValue = Integer
                .parseInt(resultObj.getJSONObject("duration").get("value").toString());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            if (null != durationValue) {
                calendar.add(Calendar.SECOND, durationValue);
            }
            Date arriveTime = calendar.getTime();

            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
            String dateStr = sdf.format(arriveTime);
            return dateStr + " 行程" + distanceTxt;
        }

        return "";
    }

    public static Result<Map<String, Long>> getDistanceAndTimeValueByTwoPoints(
        Double fromlng, Double fromlat, Double tolng, Double tolat) {

        Result<Map<String, Long>> vo = new Result<Map<String, Long>>();

        StringBuilder sb = new StringBuilder();
        sb.append(directSendURLV2);
        sb.append("?output=").append("json");
        sb.append("&origins=").append(fromlat + "," + fromlng);
        sb.append("&destinations=").append(tolat + "," + tolng);
        sb.append("&ak=").append(getAk());

        try {
            String result = getUrl(sb.toString());

            JSONObject obj = new JSONObject(result);

            Map<String, Long> map = new HashMap<String, Long>();

            if (obj.get("status").toString().equals("0")) {
                JSONObject resultObj = obj.getJSONArray("result").getJSONObject(0);

                Long distanceValue = Long.parseLong(resultObj
                    .getJSONObject("distance").get("value").toString());
                Long durationValue = Long.parseLong(resultObj
                    .getJSONObject("duration").get("value").toString());

                map.put("distance", distanceValue);//米
                map.put("time", durationValue);//秒
                vo.setResult(map);
                vo.setSuccess(true);

                return vo;
            } else {
                vo.setSuccess(false);
                return vo;
            }

        } catch (Exception e) {
            vo.setSuccess(false);
            return vo;
        }
    }

    public static boolean checkIpChina(String ip) {

        StringBuilder sb = new StringBuilder();
        sb.append(ipUrl);
        sb.append("?ip=").append(ip);
        sb.append("&ak=").append(getAk());

        try {
            String result = getUrl(sb.toString());

            JSONObject obj = new JSONObject(result);

            int status = obj.getInt("status");
            if (status == 0) {
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public static boolean checkIpChinaZhuhai(String ip) {

        StringBuilder sb = new StringBuilder();
        sb.append(ipUrl);
        sb.append("?ip=").append(ip);
        sb.append("&ak=").append(getAk());

        try {
            String result = getUrl(sb.toString());

            JSONObject obj = new JSONObject(result);

            int status = obj.getInt("status");
            if (status == 0) {
                JSONObject content = obj.getJSONObject("content");
                JSONObject address_detail = content.getJSONObject("address_detail");
                int city_code = address_detail.getInt("city_code");
                if (city_code == 140) {
                    return true;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public static JSONCheckStatus checkLogin(String url) {
        String result = getUrl(url);

        JSONObject obj = new JSONObject(result);

        JSONCheckStatus jcs = new JSONCheckStatus();

        if (obj.optBoolean("success")) {
            jcs.setSuccess(true);
            jcs.setStatus(obj.optString("status"));
            jcs.setPuaseTimeStamp(Long.parseLong(obj.optString("puaseTimeStamp")));
            jcs.setFee(obj.optDouble("fee"));
            jcs.setPuaseTime(obj.optString("puaseTime"));
            jcs.setMemo(obj.optString("memo"));
        } else {
            jcs.setSuccess(false);
        }
        return jcs;
    }

    public static Long getSmsCount(String url) {
        String result = getUrl(url);

        return Long.parseLong(result);

    }

    public static String debtsPay(String url) {
        String result = getUrl(url);

        return result;

    }

    public static String getShortUrl(String httpArg) throws UnsupportedEncodingException {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        String httpUrl = shortUrl + "?url_long=" + URLEncoder.encode(httpArg, "utf-8");

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", apikey);
            //设置超时时间
            connection.setConnectTimeout(3 * 1000);//3s
            connection.setReadTimeout(3 * 1000);//3s
            connection.connect();

            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();

            JSONObject obj = new JSONObject(result);
            JSONArray urls = obj.getJSONArray("urls");
            JSONObject urls1 = urls.getJSONObject(0);
            if (urls1.optBoolean("result")) {
                return urls1.optString("url_short");
            } else {
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }


    private static String GetResponseDataByID(String url, String postData) {
        String data = null;
        try {
            URL dataUrl = new URL(url);
            HttpURLConnection con = (HttpURLConnection) dataUrl
                .openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Proxy-Connection", "Keep-Alive");
            con.setDoOutput(true);
            con.setDoInput(true);
            //设置超时时间
            con.setConnectTimeout(3 * 1000);//3s
            con.setReadTimeout(3 * 1000);//3s

            OutputStream os = con.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            if (StringUtils.isNotBlank(postData)) {
                dos.write(postData.getBytes());
            }
            dos.flush();
            dos.close();

            InputStream is = con.getInputStream();
            data = IOUtils.toString(is, "utf-8");
            IOUtils.closeQuietly(is);
            con.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }

    public static String PostResponseDataByID(String url, String postData) {
        String data = null;
        try {
            URL dataUrl = new URL(url);
            HttpURLConnection con = (HttpURLConnection) dataUrl.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Proxy-Connection", "Keep-Alive");
            con.setDoOutput(true);
            con.setDoInput(true);
            //设置超时时间
            con.setConnectTimeout(3 * 1000);//3s
            con.setReadTimeout(3 * 1000);//3s

            OutputStream os = con.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            if (StringUtils.isNotBlank(postData)) {
                dos.write(postData.getBytes());
            }
            dos.flush();
            dos.close();

            InputStream is = con.getInputStream();
            data = IOUtils.toString(is, "utf-8");
            IOUtils.closeQuietly(is);
            con.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }

    public static String getUrl(String url) {

        String result = null;// 访问返回结果

        InputStream in = null;
        try {
            // 创建url
            URL realurl = new URL(url);
            // 打开连接
            URLConnection connection = realurl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //设置超时时间
            connection.setConnectTimeout(3 * 1000);//3s
            connection.setReadTimeout(3 * 1000);//3s
            // 建立连接
            connection.connect();
            in = connection.getInputStream();
            result = IOUtils.toString(in, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
        }

        return result;

    }

}
